package JzOffer.jz48;

/**
 * @author 张取
 * @version 1.0
 * @date 2022/1/22 下午12:26
 * JzOffer.jz48
 */

public class Codec01 {

    // Encodes a tree to a single string.
    //线性结构存储二叉树
    public String serialize(TreeNode root) {
        //前序遍历递归实现
        if(root == null){
            return "null"; //空节点
        }
        String leftStr = serialize(root.left); //序列化左子树
        String rightStr = serialize(root.right); //序列化右子树
        return String.valueOf(root.val) + "," + leftStr + "," + rightStr;
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String[] nodeStrs = data.split(","); //将字符串划分为字符数组
        int[] i = new int[]{0};
        return dfs(nodeStrs, i);
    }

    private TreeNode dfs(String[] nodeStrs, int[] i){
        String str = nodeStrs[i[0]];
        i[0]++; //堆区变量，能够实现递增遍历字符数组
        if("null".equals(str)){
            return null;
        }
        TreeNode node = new TreeNode(Integer.valueOf(str));
        node.left = dfs(nodeStrs, i);
        node.right = dfs(nodeStrs, i);
        return node;
    }
}


 class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;

      public TreeNode(int x) { val = x; }
 }
